import { ref, nextTick } from 'vue';
import type { ILeftAsideConfigItem } from '@/components/mt-edit/store/types';

export function useImageListManagement() {
  const refreshing = ref(false);

  const refreshImageList = async (
    localFile: any,
    config: Map<string, ILeftAsideConfigItem[]>,
    clearTooltipFn?: (itemId: string) => void
  ) => {
    refreshing.value = true;

    try {
      // 重新设置配置以触发响应式更新
      config.set('本地文件', [...localFile.value]);

      // 等待DOM更新
      await nextTick();

      console.log('图片列表已刷新');
    } finally {
      refreshing.value = false;
    }
  };

  const removeImageFromList = async (
    itemId: string,
    localFile: any,
    config: Map<string, ILeftAsideConfigItem[]>,
    clearStates: {
      clearTooltip?: (itemId: string) => void;
      clearDeleteState?: () => void;
    } = {}
  ) => {
    const findIndex = localFile.value.findIndex((f: ILeftAsideConfigItem) => f.id === itemId);

    if (findIndex !== -1) {
      // 删除项目
      localFile.value.splice(findIndex, 1);

      // 清理UI状态
      if (clearStates.clearDeleteState) {
        clearStates.clearDeleteState();
      }

      if (clearStates.clearTooltip) {
        clearStates.clearTooltip(itemId);
      }

      // 刷新列表
      await refreshImageList(localFile, config);

      return true;
    }

    return false;
  };

  return {
    refreshing,
    refreshImageList,
    removeImageFromList
  };
}
